﻿
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using NP.BPMReportPlatform.AUTO;
using NP.BPMReportPlatform.AUTO.Adjust.Dto;
using NP.BPMReportPlatform.AUTO.Quotation.Dto;
using NP.BPMReportPlatform.AUTO.TechnicalDependence.Dto;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.CommonEnum;
using NP.BPMReportPlatform.FlowManagement.Dto;
using NP.BPMReportPlatform.IC.ICZHYLS.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.IC
{
    public class ICQuotationAppService : BPMReportPlatformAppService, IICQuotationAppService
    {
        private readonly SqlSugarClient _db, _dbEngine;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        /// <summary>
        /// 
        public ICQuotationAppService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

      
      
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<ICQuotationOutput> GetQueryable(GetICQuotationInput input)
        {

            var listQueryable = _db.Queryable<ICQuotationHeader, BusinessProcessesNew, ICQuotationAdjustDetail>(
                    (x, bu, m) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId, JoinType.Left, x.InstanceNumber == m.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (x, bu) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))

                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerCatalog), x => x.CustomerCatalog.Equals(input.CustomerCatalog))
                .WhereIF(!string.IsNullOrWhiteSpace(input.SaleRegion), x => x.SaleRegion.Equals(input.SaleRegion))

                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerNo), x => x.CustomerNo.Contains(input.CustomerNo))
                .WhereIF(!string.IsNullOrWhiteSpace(input.NewCustomer), x => x.NewCustomer.Equals(input.NewCustomer))

                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessType), x => x.BusinessType.Equals(input.BusinessType))
                .WhereIF(!string.IsNullOrWhiteSpace(input.DeliverType), x => x.DeliverType.Equals(input.DeliverType))

                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

                .Select((x, bu, m) =>
                    new ICQuotationOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CustomerCatalog = x.CustomerCatalog,
                        SaleRegion = x.SaleRegion,
                        CustomerNo = x.CustomerNo,
                        CustomerName = x.CustomerName,
                        NewCustomer = x.NewCustomer,
                        BusinessType = x.BusinessType,
                        DeliverType = x.DeliverType,
                        ActivityName = x.ActivityName,
                        ActivityUserName = x.ActivityUserName,
                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString(),
                        UserName = bu.StartUserName,

                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }




        #region  
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<ICQuotationOutputYunFei> GetQueryableYunFei(GetICQuotationInputYunFei input)
        {

            var listQueryable = _db.Queryable<V_GIU_Quotation_Adjust_Yunfei>()
               .WhereIF(!string.IsNullOrWhiteSpace(input.客户编码), x => x.客户编码.Contains(input.客户编码))
               .WhereIF(!string.IsNullOrWhiteSpace(input.客户名称), x => x.客户名称.Contains(input.客户名称))
               .WhereIF(!string.IsNullOrWhiteSpace(input.送达方), x => x.送达方.Contains(input.送达方))
               .WhereIF(!string.IsNullOrWhiteSpace(input.产品线), x => x.产品线.Equals(input.产品线))
               .WhereIF(!string.IsNullOrWhiteSpace(input.发货工厂), x => x.发货工厂.Equals(input.发货工厂))
                 .Select((x) =>
                    new ICQuotationOutputYunFei()
                    {
                        客户编码 = x.客户编码,
                        客户名称 = x.客户名称,
                        送达方编码 = x.送达方编码,
                        送达方 = x.送达方,
                        发货工厂 = x.发货工厂,
                        产品线 = x.产品线,
                        运输净重之和 = x.运输净重之和,
                        运费金额之和 = x.运费金额之和,
                        单KG运费 = x.单KG运费,
             

                    }).MergeTable().Distinct().OrderBy(ins => ins.客户编码, OrderByType.Desc);




            return listQueryable;
        }





        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ICQuotationOutput>> GetAllAsync(GetICQuotationInput input)
        {
            // await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);

            });



            //返回结果
            return new PagedResultDto<ICQuotationOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ICQuotationOutputYunFei>> GetAllAsyncYunFei(GetICQuotationInputYunFei input)
        {
            // await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableYunFei(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            //var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            //listViewDto.ForEach(x =>
            //{
            //    x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);

            //});



            //返回结果
            return new PagedResultDto<ICQuotationOutputYunFei>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }



        #endregion


        #region IC样品导出GetQueryableExport1

        private ISugarQueryable<ExportICQuotationOutput> GetQueryableExport1(GetICQuotationInput input)
        {

            var listQueryable = _db.Queryable<ICQuotationHeader, BusinessProcessesNew,V_IC_Quotation_Adjust0>(
              (x, bu,vd0) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId, JoinType.Left, x.InstanceNumber == vd0.InstanceNumber))

                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),(x, bu,vd0) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))

                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerCatalog), x => x.CustomerCatalog.Equals(input.CustomerCatalog))
                .WhereIF(!string.IsNullOrWhiteSpace(input.SaleRegion), x => x.SaleRegion.Equals(input.SaleRegion))

                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerNo), x => x.CustomerNo.Contains(input.CustomerNo))
                .WhereIF(!string.IsNullOrWhiteSpace(input.NewCustomer), x => x.NewCustomer.Equals(input.NewCustomer))

                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessType), x => x.BusinessType.Equals(input.BusinessType))
                .WhereIF(!string.IsNullOrWhiteSpace(input.DeliverType), x => x.DeliverType.Equals(input.DeliverType))

                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

                .Select((x, bu,vd0) =>
                    new ExportICQuotationOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CustomerType = x.CustomerType,
                        UserName = x.UserName,
                        CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        SaleRegion = x.SaleRegion,
                        NewCustomer = x.NewCustomer,
                        BusinessType = x.BusinessType,
                        CustomerNo = x.CustomerNo,
                        CustomerName = x.CustomerName,
                        CustomerCatalog = x.CustomerCatalog,
                        DeliverType = x.DeliverType,
                        Deliver = x.Deliver,
                        ZDCustomerNo = x.ZDCustomerNo,
                        DeliverBusinessType = x.DeliverBusinessType,
                        Market1 = x.Market1,
                        Market2 = x.Market2,
                        ZDCustomerName = x.ZDCustomerName,
                        Remark1 = x.Remark1,
                     
 

                        ModifyBy = vd0.ModifyBy.ToString(),
                        IsKHZD = vd0.IsKHZD,
                        ProductNo = vd0.产品编码,
                        ProductName = vd0.产品名称,
                        ProductFamily = vd0.ProductFamily,
                        UpdateReason = vd0.UpdateReason,
                        DISPO = vd0.DISPO,
                        IsTY = vd0.IsTY,
                        BusinessOpportunities = vd0.BusinessOpportunities,
                        BusinessName = vd0.BusinessName,
                        Packing = vd0.Packing,
                        FixedMonthlyAmount = vd0.FixedMonthlyAmount,
                        MoneyUnit = vd0.MoneyUnit,
                        Unit = vd0.Unit,
                        RMCC1 = vd0.RMCC1.ToString(),
                        Cost = vd0.Cost.ToString(),
                        PriceSJML = vd0.PriceSJML.ToString(),
                        SAP同步状态 = vd0.SapStatus.ToString().Replace("NULL", "失败").Replace("0", "未同步").Replace("1", "成功"),
                        是否低于参考价 = vd0.AdjustPercent >= 0 ? "否" : "是",
                        RMCCccc = vd0.RMCCccc.ToString(),
                        ToPrice = vd0.ToPrice.ToString(),
                        AdjustPercent1 = vd0.AdjustPercent1.ToString(),
                        CompetitorPrice = decimal.Parse(vd0.CompetitorPrice).ToString(),
                        AdjustPercent = vd0.AdjustPercent.ToString(),
                        Competitor = vd0.Competitor.ToString(),
                        CompetitorPrice1 = vd0.CompetitorPrice1.ToString(),
                        Notes = vd0.Notes.ToString(),
                        ProcessCost = vd0.ProcessCost.ToString(),
                        Freight = vd0.Freight.ToString(),
                        ManagerPrice = vd0.ManagerPrice.ToString(),
                        GMPrice = vd0.GMPrice.ToString(),
                        MaterialsTypeId = vd0.MaterialsTypeId.ToString(),

                        CPTX_Value = vd0.VOC,
                        销售报价 = vd0.销售单价,
                        毛利 = vd0.ML,
                        总成本 = vd0.总成本,
                        流程最终报价 = vd0.流程最终报价,
                        IfSuccessed = vd0.ifSuccessed,

                        销售部负责人 = x.XSBFZRname.ToString(),
                        行业总经理 = x.HYZJLname.ToString(),
                        产品管理 = x.CPGLname.ToString(),
                        PDT负责人 = x.PDTname.ToString(),
                        IC总经理 = x.ZJLname.ToString(),
                        结案人 = x.FinishUserName.ToString(),
                        PriceBegTime = x.PriceBegTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        PriceEndtime = x.PriceEndtime.ToString("yyyy-MM-dd HH:mm:ss"),

                        OrderStatus = bu.ProcessStatusName,
                        FinishTime = bu.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    

           
           }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            //var listQueryable = _db.UnionAll(listQueryable1, listQueryable2).Select<ExportICQuotationOutput>().MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }


        private ISugarQueryable<ExportICQuotationOutputYunFei> GetQueryableExport1YunFei(GetICQuotationInputYunFei input)
        {

         var listQueryable = _db.Queryable<V_GIU_Quotation_Adjust_Yunfei>()
            .WhereIF(!string.IsNullOrWhiteSpace(input.客户编码), x => x.客户编码.Contains(input.客户编码))
            .WhereIF(!string.IsNullOrWhiteSpace(input.客户名称), x => x.客户名称.Contains(input.客户名称))
            .WhereIF(!string.IsNullOrWhiteSpace(input.送达方), x => x.送达方.Contains(input.送达方))
            .WhereIF(!string.IsNullOrWhiteSpace(input.产品线), x => x.产品线.Equals(input.产品线))
            .WhereIF(!string.IsNullOrWhiteSpace(input.发货工厂), x => x.发货工厂.Equals(input.发货工厂))
              .Select((x) =>

                 new ExportICQuotationOutputYunFei()
                    {
                     客户编码 = x.客户编码,
                     客户名称 = x.客户名称,
                     送达方编码 = x.送达方编码,
                     送达方 = x.送达方,
                     发货工厂 = x.发货工厂,
                     产品线 = x.产品线,
                     运输净重之和 = x.运输净重之和,
                     运费金额之和 = x.运费金额之和,
                     单KG运费 = x.单KG运费,


                 }).MergeTable().Distinct().OrderBy(ins => ins.客户编码, OrderByType.Desc);

            return listQueryable;
        }
        #endregion

        #region IC样品导出Export1Async
        /// <summary>
        /// 报表导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportICQuotationOutput>> Export1Async(GetICQuotationInput input)
        {
    
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableExport1(input);
            var listViewDto = await listQueryable.ToListAsync();




            var i = 1;
            listViewDto.ForEach(x => x.SerialNumber = i++.ToString());
            return listViewDto;
        }

        #endregion

        /// <summary>
        /// 报表导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportICQuotationOutputYunFei>> Export1AsyncYunFei(GetICQuotationInputYunFei input)
        {

            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableExport1YunFei(input);
            var listViewDto = await listQueryable.ToListAsync();




            var i = 1;
            listViewDto.ForEach(x => x.SerialNumber = i++.ToString());
            return listViewDto;
        }
    }
}
